from flask import request
from flask import Blueprint,render_template, jsonify, redirect, url_for, session
from exts import mail, db
from flask_mail import Message
import string
import random
from models import EmailCaptchaModel, UserModel, StudentConfirmationModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                return '未找到该用户，请先注册'
            if check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect('/')
            else:
                return redirect(url_for('auth.login'))
        else:
            list_log = []
            for error in form.errors.values():
                list_log.append(error[0])
            return ', '.join(list_log)




@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    elif request.method == 'POST':
        form = RegisterForm(request.form)
        if form.validate():
            teacher = request.form.get('student_confirm')
            confirm = StudentConfirmationModel.query.filter_by(teacher=teacher).first()
            if not confirm:
                return 'CFMZ学生验证失败！'
            else:
                email = form.email.data
                username = form.username.data
                password = form.password.data
                user = UserModel(email=email, username=username, password=generate_password_hash(password))
                db.session.add(user)
                db.session.commit()
                return redirect(url_for('auth.login'))
        else:
            list_reg = []
            for error in form.errors.values():
                list_reg.append(error[0])
            return ', '.join(list_reg)




@bp.route('/captcha/email')
def get_email_captcha():
     email = request.args.get('email')
     source = string.digits*4
     captcha = random.sample(source,4)
     captcha = ''.join(captcha)
     message = Message(subject='CFMZ学生社区验证码', recipients=[email], body=f'CFMZ学生社区验证码,您的验证码为:{captcha}')
     mail.send(message)
     email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
     db.session.add(email_captcha)
     db.session.commit()
     return jsonify({'code': 200, 'message': "", 'data': None})

